/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package taikai.stopwatch;

import java.io.Serializable;
import java.text.ParseException;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JLabel;
import javax.swing.JProgressBar;
import javax.swing.JToggleButton;

public final class StopWatch extends TimerTask implements Serializable {

    private boolean running = false;
    private final Calendar time = GregorianCalendar.getInstance();
    private JLabel label = null;
    private JProgressBar progressBar = null;
    private String duration = "10:00";
    private JToggleButton toggleButton;

    public StopWatch() {
        new Timer("StopWatch").scheduleAtFixedRate(this, 1000, 1000);
        reset();
    }

    @Override
    public void run() {
        if (running) {
            if (time.getTimeInMillis() > 0) {
                time.add(Calendar.SECOND, -1);
            }
            displayTime();
        }
    }

    private void displayTime() {
        if (getLabel() != null) {
            getLabel().setText(String.format("%1$tM:%1$tS", time));
        }
        if (getProgressBar() != null) {
            getProgressBar().setValue((int) time.getTimeInMillis());
        }
    }

    public void press() {
        running = !running;
        updateToggleButtonText();
    }

    private void updateToggleButtonText() {
        if (running) {
            toggleButton.setText("Pause");
        } else {
            toggleButton.setText("Start");
        }
    }

    boolean isRunning() {
        return running;
    }

    public JLabel getLabel() {
        return label;
    }

    public void setLabel(JLabel label) {
        this.label = label;
        displayTime();
    }

    public void reset() {
        running = false;
        time.setTimeInMillis(0);
        time.set(Calendar.MINUTE, Integer.parseInt(duration.split(":")[0]));
        time.set(Calendar.SECOND, Integer.parseInt(duration.split(":")[1]));

        if (progressBar != null) {
            progressBar.setMaximum((int) time.getTimeInMillis());
            progressBar.setValue(progressBar.getMaximum());
        }

        displayTime();
    }

    public JProgressBar getProgressBar() {
        return progressBar;
    }

    public void setProgressBar(JProgressBar progressBar) {
        this.progressBar = progressBar;
    }

    public void setDuration(String string) throws ParseException {
        duration = string;
        reset();
    }

    public void setToggleButton(JToggleButton jToggleButton) {
        this.toggleButton = jToggleButton;
        updateToggleButtonText();
    }

    /**
     * @return the toggleButton
     */
    public JToggleButton getToggleButton() {
        return toggleButton;
    }
}
